package com.djf.djfcs.config;

import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.Properties;

/**
 * 自定义表分片算法
 * 根据create_time字段按月分表
 */
@Component
public class CustomTableShardingAlgorithm implements StandardShardingAlgorithm<LocalDateTime> {

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMM");
    private String tablePrefix;

    @Override
    public void init(Properties props) {
        // 从配置中获取表前缀
        this.tablePrefix = props.getProperty("table-prefix", "order_");
    }

    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<LocalDateTime> shardingValue) {
        LocalDateTime createTime = shardingValue.getValue();
        String suffix = createTime.format(FORMATTER);
        String targetTable = tablePrefix + suffix;
        
        // 检查目标表是否在可用表列表中
        for (String tableName : availableTargetNames) {
            if (tableName.equals(targetTable)) {
                return targetTable;
            }
        }
        
        // 如果没有找到匹配的表，返回第一个可用表（或抛出异常）
        throw new IllegalArgumentException("No matching table found for date: " + createTime + ", target table: " + targetTable);
    }

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, RangeShardingValue<LocalDateTime> shardingValue) {
        // 范围查询时，返回所有可能的表
        return availableTargetNames;
    }

    @Override
    public String getType() {
        return "CUSTOM_TABLE";
    }

    @Override
    public Properties getProps() {
        return null;
    }
}